package com.bnlr.lrparking.appui.publish;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.event.PublishFinishEvent;
import com.bnlr.lrparking.model.AlterPublishDetailBean;
import com.bnlr.lrparking.model.BaseArrayBean;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.util.CommonUtil;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.lrparking.view.ClearEditText;
import com.bnlr.lrparking.view.SampleEditTextWatcher;
import com.bnlr.lrparking.widget.ConvertHelper;
import com.bnlr.lrparking.widget.boarddialog.InputBoardDialog;
import com.bnlr.lrparking.widget.boarddialog.InputRentBoardDialog;
import com.bnlr.lrparking.widget.boarddialog.KeyBoardDialog;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 发布下一级  出租出售
 */
public class PublishNextActivity extends BaseActivity {
    @BindView(R.id.tv_stall_property)
    TextView tvStallProperty;
    @BindView(R.id.tv_build_time)
    TextView tvBuildTime;
    private Unbinder unbinder;
    private PublishIntentBean bean;
    @BindView(R.id.tv_nav_title)
    TextView tvTitle;
    @BindView(R.id.tv_year_limit)
    TextView yearLimit;
    @BindView(R.id.publish_place_advantage)
    ClearEditText etAdvantage;
    @BindView(R.id.tv_price_type)
    TextView priceType;
    @BindView(R.id.tv_price)
    TextView tvPrice;
    @BindView(R.id.et_name)
    ClearEditText etName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.et_publish_description)
    EditText etDesc;
    @BindView(R.id.radioGroup)
    RadioGroup radioGroup;
    @BindView(R.id.text_count_limit)
    TextView textCountLimit;
    @BindView(R.id.agree_clause)
    CheckBox agreeCheckBox;
    @BindView(R.id.rl_object)
    RelativeLayout rlObject;
    @BindView(R.id.publish_object)
    TextView tvPublishObject;
    @BindView(R.id.man)
    RadioButton rbMan;
    @BindView(R.id.rb_woman)
    RadioButton rbWoman;
    @BindView(R.id.rl_property)
    RelativeLayout rlProperty;
    @BindView(R.id.rl_build_time)
    RelativeLayout rlBuildTime;
    @BindView(R.id.rl_rent_duration)
    RelativeLayout rlRentDuration;
    @BindView(R.id.tv_rent_duration)
    TextView tvRentDuration;
    @BindView(R.id.publish)
    TextView tvPublish;
    private String requestType = "10";
    private String zjCount = "";
    private String username, publishPhone;
    private String year = "";
    private ArrayList<String> targetType = new ArrayList<>();
    private ArrayList<String> propertyType = new ArrayList<>();
    private OptionsPickerView pvCustomOptions,propertyPicker,timePickerView,rentDurationPicker;
    private int targetTag = 0;
    private AlterPublishDetailBean.DataBean alterBean;
    private ArrayList<ArrayList<String>> monthList = new ArrayList<>();
    private ArrayList<String> yearList = new ArrayList<>();
    private int stallTypeId;
    private List<String> rentDurationData = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_publish_next);
        unbinder = ButterKnife.bind(this);
        username = AppConfig.getInstance().getString("userName", "");
        publishPhone = username;
        if (!username.equals("")) {
            tvPhone.setText(username.substring(0, 3) + "****" + username.substring(7));
        }
        bean = getIntent().getParcelableExtra("publish_data");
        alterBean = getIntent().getParcelableExtra("alter_next_publish");
        if (bean.isAlter() && alterBean != null) {

            etAdvantage.setText(ConvertHelper.convertToString(alterBean.getSpaceAdvan()));
            tvPrice.setText(ConvertHelper.convertToString(alterBean.getPrice()) + ConvertHelper.convertToString(alterBean.getPriceUnit()));
            zjCount = ConvertHelper.convertToString(alterBean.getPrice());
            if (ConvertHelper.convertToString(alterBean.getUserName()).endsWith("先生")) {
                rbMan.setChecked(true);
                etName.setText(ConvertHelper.convertToString(alterBean.getUserName()).replace("先生", ""));
            } else if (ConvertHelper.convertToString(alterBean.getUserName()).endsWith("女士")) {
                rbWoman.setChecked(true);
                etName.setText(ConvertHelper.convertToString(alterBean.getUserName()).replace("女士", ""));
            } else {
                etName.setText(ConvertHelper.convertToString(alterBean.getPrice()));
            }
            tvPhone.setText(CommonUtil.formatPhoneNumber(alterBean.getPhone()));
            publishPhone = alterBean.getPhone();
            etDesc.setText(ConvertHelper.convertToString(alterBean.getDescription()));
            targetTag = alterBean.getIsSaleToAll();
            if (targetTag == 0) {
                tvPublishObject.setText("仅对本小区业主销售");
            } else {
                tvPublishObject.setText("可对外销售");
            }
            if (alterBean.getIsHaveSpace() == 0) {
                tvStallProperty.setText("有");
                yearLimit.setText("永久");
                year = "";
                yearLimit.setEnabled(false);

            } else {
                tvStallProperty.setText("无");
                if (ConvertHelper.convertToString(alterBean.getDateLine()).length() > 0) {
                    year = ConvertHelper.convertToString(alterBean.getDateLine()).replace("年", "");
                }
                yearLimit.setText(ConvertHelper.convertToString(alterBean.getDateLine()));
                yearLimit.setEnabled(true);
            }
            tvBuildTime.setText(alterBean.getSpaceBuildTime());
        }
        tvTitle.setText(bean.getTitle());
        if (bean.getTag() == 1) {
            requestType = "10";
            priceType.setText("租金");
            etDesc.setHint("(选填)详细的描述会大大增加快速出租的机会！可以介绍车位吸引人的地方，交通和周边环境等。");
            rlObject.setVisibility(View.GONE);
            rlProperty.setVisibility(View.GONE);
            rlBuildTime.setVisibility(View.GONE);
            getRentDuration();
        } else {
            requestType = "11";
            priceType.setText("售价");
            etDesc.setHint("(选填)详细的描述会大大增加快速出售的机会！可以介绍车位吸引人的地方，交通和周边环境等");
            rlRentDuration.setVisibility(View.GONE);
        }
        initListener();
        targetType.add("仅对本小区业主销售");
        targetType.add("可对外销售");
        propertyType.add("有");
        propertyType.add("无");
        initCustomOptionPicker();
        initPropertyPicker();
        initTimePicker();
    }

    /**
     * 获取租用时长
     */
    private void getRentDuration() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "GetLendTimes");
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<RentDurationBean>(baseContext, true, RentDurationBean.class) {
                        @Override
                        public void doWork(RentDurationBean data, String code) {
                            if ("1".equals(code)) {
                                if (data!= null && data.getData() != null) {
                                    rentDurationData.addAll(data.getData());
                                    initRentDurationPicker();
                                }
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (!code.equals("1")) {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    private void initRentDurationPicker() {
        rentDurationPicker = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                tvRentDuration.setText(rentDurationData.get(options1));
            }
        }).build();
        rentDurationPicker.setPicker(rentDurationData);
    }


    private void initListener() {
        etDesc.addTextChangedListener(new SampleEditTextWatcher() {
            @Override
            public void afterTextChanged(Editable s) {
                int length = s.toString().length();
                textCountLimit.setText(length + "/300");
            }
        });
        agreeCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    agreeCheckBox.setChecked(true);
                } else {
                    agreeCheckBox.setChecked(false);
                }
            }
        });
    }

    @OnClick({R.id.tv_issueagreement, R.id.publish, R.id.tv_phone, R.id.tv_price,
            R.id.rl_agree, R.id.tv_year_limit, R.id.publish_object,R.id.tv_stall_property, R.id.tv_build_time
    ,R.id.tv_rent_duration})
    public void publishOnClick(View view) {
        switch (view.getId()) {
            case R.id.tv_issueagreement:
                Intent intent = new Intent(baseContext, WebActivity.class);
                intent.putExtra("tag", 7);
                startActivity(intent);
                break;
            case R.id.tv_year_limit:
                etAdvantage.clearFocus();
                InputRentBoardDialog dialog3 = new InputRentBoardDialog(this, year, "年");
                dialog3.setOnDialogResultListener(new InputRentBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String result) {
                        if (!"cancel".equals(result)) {
                            yearLimit.setText(result);
                            if (result.equals("")) {
                                year = "";
                            } else {
                                year = result.substring(0, result.length() - 1);
                            }
                        }
                    }
                });
                dialog3.show();
                break;
            case R.id.tv_phone:
                KeyBoardDialog dialog = new KeyBoardDialog(this, publishPhone);
                dialog.setOnDialogResultListener(new KeyBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String result) {
                        if (result.equals("some")) {
                            ToastUtils.showShort("此手机号无需再次验证");
                        } else if (!result.equals("fail")) {
                            publishPhone = result;
                            tvPhone.setText(publishPhone.substring(0, 3) + "****" + publishPhone.substring(7));
                        }
                    }
                });
                dialog.show();
                break;
            case R.id.tv_price:
                if (bean.getTag() == 2) {
                    InputBoardDialog dialog1 = new InputBoardDialog(this, zjCount, "元");
                    dialog1.setOnDialogResultListener(new InputBoardDialog.OnDialogResultListener() {
                        @Override
                        public void onResult(String result) {
                            if (!"cancel".equals(result)) {
                                tvPrice.setText(result);
                                if (result.equals("")) {
                                    zjCount = "";
                                } else {
                                    zjCount = result.substring(0, result.length() - 1);
                                }
                            }
                        }
                    });
                    dialog1.show();
                } else if (bean.getTag() == 1) {
                    InputRentBoardDialog dialog1 = new InputRentBoardDialog(this, zjCount, "元/月");
                    dialog1.setOnDialogResultListener(new InputRentBoardDialog.OnDialogResultListener() {
                        @Override
                        public void onResult(String result) {
                            if (!"cancel".equals(result)) {
                                tvPrice.setText(result);
                                if (result.equals("")) {
                                    zjCount = "";
                                } else {
                                    zjCount = result.substring(0, result.length() - 3);
                                }
                            }
                        }
                    });
                    dialog1.show();
                }
                break;
            case R.id.rl_agree:
                if (agreeCheckBox.isChecked()) {
                    agreeCheckBox.setChecked(false);
                } else {
                    agreeCheckBox.setChecked(true);
                }
                break;
            case R.id.publish:
                publish();
                break;
            case R.id.publish_object:
                pvCustomOptions.show();
                break;
            case R.id.tv_stall_property:
                propertyPicker.show();
                break;
            case R.id.tv_build_time:
                timePickerView.show();
                break;
            case R.id.tv_rent_duration:
                if (rentDurationPicker != null) {
                    rentDurationPicker.show();
                }
                break;
            default:
                break;
        }
    }

    /**
     * 发布
     */
    private void publish() {
        if (agreeCheckBox.isChecked()) {
            ToastUtils.showShort("请您先同意发布信息服务协议");
            return;
        }
        String year = yearLimit.getText().toString();
        if (TextUtils.isEmpty(year)) {
            ToastUtils.showShort("请输入使用年限");
            return;
        }
        String advantage = etAdvantage.getText().toString();
        String user = etName.getText().toString();
        if (TextUtils.isEmpty(user)) {
            ToastUtils.showShort("请输入联系人");
            return;
        }
        if (bean != null && bean.getTag() == 1) {
            if (TextUtils.isEmpty(tvRentDuration.getText().toString())) {
                ToastUtils.showShort("请选择出租时长");
                return;
            }
        }
        String desc = etDesc.getText().toString();
        tvPublish.setEnabled(false);
        try {
            mRequest = NoHttp.createStringRequest(Urls.SPACE_IP, LrConstant.POST);
            mRequest.add("action", "PublishSpace");
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("type", requestType);
            mRequest.add("photo", bean.getImgString());
            mRequest.add("authenphoto", bean.getFileString());
            mRequest.add("size", bean.getMj());
            mRequest.add("address", bean.getAddress());
            mRequest.add("title", bean.getPublishTitle());
            mRequest.add("lat", bean.getLatitude());
            mRequest.add("lng", bean.getLongitude());
            mRequest.add("number", bean.getCarNumber());
            mRequest.add("cityName", bean.getCityName());
            mRequest.add("areaName", bean.getAreaName());
            mRequest.add("description", desc);
            if (alterBean != null) {
                mRequest.add("parkSpaceId", alterBean.getId());
            }
            if (radioGroup.getCheckedRadioButtonId() == R.id.man) {
                mRequest.add("username", user + "先生");
            } else {
                mRequest.add("username", user + "女士");
            }
            mRequest.add("spacetype", bean.getCarPlaceId());
            if (zjCount.equals("")) {
                zjCount = "0";
            }
            mRequest.add("price", zjCount);
            mRequest.add("phone", publishPhone);
            if (requestType.equals("10")) {
                mRequest.add("priceunit", "元/月");
            } else {
                mRequest.add("priceunit", "元");
                mRequest.add("isSaleToAll", targetTag);
            }
            mRequest.add("floorNum", bean.getFloor());
            mRequest.add("dateLine", year);
            mRequest.add("spaceAdvan", advantage);
            mRequest.add("parkingName",bean.getHouseName());
            mRequest.add("isHaveSpace",tvStallProperty.getText().toString().equals("有")?0:1);
            mRequest.add("spaceBuildTime",tvBuildTime.getText().toString());
            if (bean != null && bean.getTag() == 1) {
                mRequest.add("lendTime",tvRentDuration.getText().toString());
            }
            // 添加到请求队列+
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<BaseArrayBean>(baseContext, true, BaseArrayBean.class) {
                        @Override
                        public void doWork(BaseArrayBean data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {

                            if ("1".equals(code)) {
                                CarCommon carCommon = new CarCommon();
                                carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
                                    @Override
                                    public void setSure() {
                                        EventBus.getDefault().post(new PublishFinishEvent());
                                        startActivity(MyPublishActivity.class);
                                        finish();
                                    }
                                });
                                carCommon.ReminderDialog(PublishNextActivity.this, "您已发布成功，请等待审核。", "提示");
                            } else {
                                zjCount = "";
                                try {
                                    ToastUtils.showShort(obj.getString("msg"));
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            tvPublish.setEnabled(true);

                        }
                    }, true);
        } catch (Exception e) {

        }
    }

    private void initCustomOptionPicker() {
        pvCustomOptions = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                tvPublishObject.setText(targetType.get(options1));
                if (options1 == 0) {
                    targetTag = 0;
                } else {
                    targetTag = 1;
                }

            }
        }).setLayoutRes(R.layout.pickerview_time, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        pvCustomOptions.returnData();
                        pvCustomOptions.dismiss();
                    }
                });
            }
        }).isDialog(false).build();
        pvCustomOptions.setPicker(targetType);
    }
    private void initPropertyPicker() {
        propertyPicker = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                tvStallProperty.setText(propertyType.get(options1));
                if (options1 == 0) {
                    yearLimit.setText("永久");
                    yearLimit.setEnabled(false);
                } else {
                    year = "";
                    yearLimit.setText("");
                    yearLimit.setEnabled(true);
                }

            }
        }).setLayoutRes(R.layout.pickerview_time, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        propertyPicker.returnData();
                        propertyPicker.dismiss();
                    }
                });
            }
        }).isDialog(false).build();
        propertyPicker.setPicker(propertyType);
    }
    private void initTimePicker() {
        for (int i = 1900; i < 2081; i++) {
            yearList.add(i+"年");
            ArrayList<String> month = new ArrayList<>();
            for (int j = 1; j < 13; j++) {
                month.add(j+"月");
            }
            monthList.add(month);
        }

        timePickerView = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = yearList.get(options1)+monthList.get(options1).get(option2) ;
                tvBuildTime.setText(tx);

            }
        }).setLayoutRes(R.layout.pickerview_time, new CustomListener() {
            @Override
            public void customLayout(View v) {
                final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                tvSubmit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        timePickerView.returnData();
                        timePickerView.dismiss();
                    }
                });
            }
        }).isDialog(false).build();
        timePickerView.setPicker(yearList,monthList);


    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbinder.unbind();
    }


}
